package com.kasax.skin.support;

import android.app.Activity;
import android.app.Application;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.kasax.skin.support.utils.LogUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class SkinActivityLifeCallback implements Application.ActivityLifecycleCallbacks {
    private Map<Activity, SkinLayoutFactory> factoryMap = new HashMap<>();

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        /**
         * 更新状态栏
         */
        SkinThemeUtils.updateStatusBarColor(activity);
        /**
         * 更新字体
         */
        Typeface skinTypeFace = SkinThemeUtils.getSkinTypeFace(activity);

        LayoutInflater layoutInflater = LayoutInflater.from(activity);
        try {
            Field mFactorySet = LayoutInflater.class.getDeclaredField("mFactorySet");
            mFactorySet.setAccessible(true);
            mFactorySet.setBoolean(layoutInflater, false);
        } catch (Exception e) {
            LogUtils.e(getClass(), e);
        }

        // 添加自定义创建View 工厂
        SkinLayoutFactory skinLayoutFactory = new SkinLayoutFactory(activity, skinTypeFace);
        layoutInflater.setFactory2(skinLayoutFactory);


        // 注册观察者
        SkinManager.getInstance().addObserver(skinLayoutFactory);
        factoryMap.put(activity, skinLayoutFactory);
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {

    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        // 删除观察者
        SkinLayoutFactory layoutFactory = factoryMap.remove(activity);
        SkinManager.getInstance().deleteObserver(layoutFactory);
    }
}
